﻿using DevExpress.Mvvm;
using log4net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PlaceOrder_Core.Models.QuanYi;
using PlaceOrder_Core.QuanYi;
using PlaceOrder_Core.Services.Instances;
using PlaceOrder_Core.Services.Interfaces;
using PlaceOrder_Shared.Models.Common;
using PlaceOrder_Shared.Models.Daily;
using PlaceOrder_Shared.Models.QaingPing;
using PlaceOrder_Shared.Models.Trade;
using PlaceOrder_Shared.ModelsToLily;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using WatsonWebsocket;
using WebSocketSharp;
using WebSocket = WebSocketSharp.WebSocket;
using WebSocketException = WebSocketSharp.WebSocketException;
using WebSocketState = WebSocketSharp.WebSocketState;

namespace PlaceOrder_Core.Helper
{
    public class ClientWebSocketHelper:IDisposable
    {
        private static string serverUri = $"{DataHelper.BaseConfig.WebSocketUrl}/websocket/{UserHelper.Token}";
        public static int GlobalTimeOut = 12; //连接服务器超时时间
                                                //private  WebSocket clientWebSocket; //客户端websocket

        private bool isDisposed = false;
        public void Dispose()
        {
            isDisposed = true;

            if (clientWebSocket != null)
            {
                // 移除 Closed 事件处理程序
                clientWebSocket.OnClose -= ClientWebSocket_OnClose1;
                clientWebSocket.OnClose -=LilyWebSocket_OnClose;
                AppLog.WriteInfo("websocket彻底关闭连接！");
                clientWebSocket.Close();
            }
        }
        public ClientWebSocketHelper()
        {
          
        }
        private readonly IDailyData _dailyData;
        public ClientWebSocketHelper(IDailyData dailyData)
        {
            _dailyData = dailyData;
        }
        private Thread WebSocketClientThread;//客户端线程
        private Thread MainSocket;//主线程
        private Thread WatchDogThread;//心跳线程
        private Thread SendMessageThread;//获取数据线程
        public void Init()
        {
            try
            {


                //********** Log ***********//
                AppLog.WriteInfo("ClientWebSocketHelper"+"地址："+ serverUri);
                //**************************//

                WebSocketClientThread = new Thread(new ThreadStart(ClientWebSocketStart));
                WebSocketClientThread.Start();
            }
            catch (Exception ex)
            {
                //********** Log ***********//
                AppLog.WriteInfo("ClientWebSocketHelper" + "地址：" + serverUri+ex.Message);
                //**************************//
            }
            finally
            { }
        }

        private void ClientWebSocketStart()
        {
            try
            {
                MainSocket = Thread.CurrentThread;
                //while (true)
                //{
                //    //try
                //    //{
                //    //    clientWebSocket = new WebSocket(serverUri);
                //    //    //********** Log ***********//
                //    //    AppLog.WriteInfo("ClientWebSocketStart"+ "Start", "连接建立!");
                //    //    //**************************//
                //    //    clientWebSocket.OnMessage += ClientWebSocket_OnMessage;
                //    //    break;
                //    //}
                //    //catch
                //    //{
                //    //    //********** Log ***********//
                //    //    AppLog.WriteInfo("ClientWebSocketStart" + "Start", "连接异常!");
                //    //    //**************************//
                //    //    Thread.Sleep(5000);
                //    //}
                //}
                WatchDogThread = new Thread(new ThreadStart(WatchDogStart));
                WatchDogThread.Start();

                //SendMessageThread = new Thread(new ThreadStart(SendMessageStart));
                //SendMessageThread.Start();
            }
            catch(Exception ex) 
            {
            }

        }
        private bool SubscribeTradeSucceeded = false; //订阅交易信息(是否websocket连接成功）
        private bool SubscribeVolumeSucceeded = false; //订阅龙虎榜信息
        private bool SubscribeLilySucceeded = false; //订阅lily信息（我的服务端订阅刘老师服务端）
        private static JsonSerializerSettings settings = new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore,
            MissingMemberHandling = MissingMemberHandling.Ignore
        };
        #region 客户端

        /// <summary>
        /// 核心方法(客户端连接至服务端）,isIndex说明要发送登录的信息
        /// </summary>
        /// <param name="ServerIP"></param>
        /// <param name="ServerPort"></param>
        /// <returns></returns>
        public bool ClientStartConnectToServer(string ServerIP, int ServerPort,bool isIndex=false)
        {
            try
            {
                //string ServerIP = "172.16.10.123";
                this.ServerIP = ServerIP;
                this.ServerPort = ServerPort;
                //client = null;
                Uri uri = new Uri($"ws://{ServerIP}:{ServerPort}");
                client = new WatsonWsClient(uri);
                if (UserHelper.TradeLimit == null)
                {
                    UserHelper.TradeLimit = new UserTradeLimit();
                }
                //UserHelper.TradeLimit.InitMaxVolume = _dailyData.GetLilyTradeLimit(UserHelper.UserID);
                //SendMessageThread = new Thread(new ThreadStart(SendMessageStart));
                //SendMessageThread.Start();
                ClientSendMessageStart();
                Thread.Sleep(20);
                if (!client.Connected)
                {
                    return false;
                }
                QuanYiServerResponseClass qsr = new QuanYiServerResponseClass();
                qsr.DataType = QuanYiServerResponseClass.DataTypeEnum.Login;
                qsr.UserID = UserHelper.UserID;
                qsr.Token = UserHelper.Token;
                qsr.IsIndex = isIndex;
                
                bool res = SendResponseToServer(qsr);
                if (!res)
                {
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "clientWebSocket" + "StartConnection" + ex.StackTrace);
                return false;
            }
        }




        public async Task<bool> ClientStartConnectToServerAsync(string ServerIP, int ServerPort, bool isIndex = false)
        {
            try
            {
                this.ServerIP = ServerIP;
                this.ServerPort = ServerPort;
                client = null;
                Uri uri = new Uri($"ws://{ServerIP}:{ServerPort}");
                client = new WatsonWsClient(uri);

                if (UserHelper.TradeLimit == null)
                {
                    UserHelper.TradeLimit = new UserTradeLimit();
                }
                //UserHelper.TradeLimit.InitMaxVolume = _dailyData.GetLilyTradeLimit(UserHelper.UserID);

                // 开始发送消息
                ClientSendMessageStart();

                // 等待连接
                await Task.Run(() =>
                {
                    while (!client.Connected)
                    {
                        Task.Delay(2000).Wait();
                    }
                });

                if (!client.Connected)
                {
                    return false;
                }

                QuanYiServerResponseClass qsr = new QuanYiServerResponseClass
                {
                    DataType = QuanYiServerResponseClass.DataTypeEnum.Login,
                    UserID = UserHelper.UserID,
                    Token = UserHelper.Token,
                    IsIndex = isIndex
                };

                bool res = await SendResponseToServerAsync(qsr);
                return res;
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "clientWebSocket" + "StartConnection" + ex.StackTrace);
                return false;
            }
        }

        private async Task<bool> SendResponseToServerAsync(QuanYiServerResponseClass qsr)
        {
            // Implement your async sending logic here
            // For example, sending a message to the server asynchronously
            return await Task.Run(() => SendResponseToServer(qsr));
        }

        /// <summary>
        /// 发给服务端线程
        /// </summary>
        /// 
        private void ClientSendMessageStart()
        {
            if (client == null)
            {
                return;
            }
            // 检查 WebSocket 是否已经连接或正在连接
            if (client.Connected == true)
            {
                AppLog.WriteInfo("WebSocket is already started or connecting.");
                return;
            }
            client.ServerConnected -= Client_ServerConnected;

            client.ServerConnected += Client_ServerConnected;
            client.ServerDisconnected -= Client_ServerDisconnected;
            client.ServerDisconnected += Client_ServerDisconnected;
            client.MessageReceived -= Client_MessageReceived;
            client.MessageReceived += Client_MessageReceived;
            client.KeepAliveInterval = 30;
            try
            {
                // 启动 WebSocket 连接
                client.Start();
                AppLog.WriteInfo("WebSocket connection started.");
            }
            catch (Exception ex)
            {
                AppLog.WriteError($"ClientSendMessageStart---Error starting WebSocket: {ex.Message}，{ex.StackTrace}");

            }
        }

        //private async void ClientSendMessageStart()
        //{
        //    if (client == null)
        //    {
        //        return;
        //    }

        //    // 检查 WebSocket 是否已经连接或正在连接
        //    if (client.Connected)
        //    {
        //        AppLog.WriteInfo("WebSocket 已经启动或正在连接中。");
        //        return;
        //    }

        //    // 解绑旧事件并绑定新的事件
        //    client.ServerConnected -= Client_ServerConnected;
        //    client.ServerConnected += Client_ServerConnected;
        //    client.ServerDisconnected -= Client_ServerDisconnected;
        //    client.ServerDisconnected += Client_ServerDisconnected;
        //    client.MessageReceived -= Client_MessageReceived;
        //    client.MessageReceived += Client_MessageReceived;
        //    client.KeepAliveInterval = 30;

        //    int retryDelay = 5000;  // 每次重试的延迟时间（毫秒）
        //    int maxRetryAttempts = 10; // 最大重试次数
        //    int longRetryDelay = 60000; // 更长的重试延迟时间（毫秒）
        //    int attempt = 0;

        //    while (!client.Connected)
        //    {
        //        try
        //        {
        //            // 启动 WebSocket 连接
        //            client.Start();
        //            AppLog.WriteInfo("WebSocket 连接已启动。");

        //            // 如果成功连接，跳出循环
        //            if (client.Connected)
        //            {
        //                AppLog.WriteInfo("OrderViewModel 和 lxw 服务器连接成功。");
        //                return;
        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            AppLog.WriteError($"ClientSendMessageStart---启动 WebSocket 时出错: {ex.Message}, {ex.StackTrace}");
        //        }

        //        attempt++;
        //        AppLog.WriteInfo($"正在重试连接... 第 {attempt} 次，共 {maxRetryAttempts} 次");

        //        // 重试之前等待指定的时间
        //        await Task.Delay(retryDelay);

        //        // 达到最大重试次数后，等待更长时间再进行下一次重试
        //        if (attempt >= maxRetryAttempts)
        //        {
        //            AppLog.WriteInfo($"达到最大重试次数。等待 {longRetryDelay / 1000} 秒后再重试...");
        //            await Task.Delay(longRetryDelay);
        //            attempt = 0; // 重置尝试次数，继续循环重试
        //        }
        //    }

        //    if (!client.Connected)
        //    {
        //        AppLog.WriteError("经过多次重试后，WebSocket 仍然无法连接。需要人工干预。");
        //    }
        //}



        private bool isReconnecting = false;
        private System.Timers.Timer reconnectTimer;
        private void Client_ServerDisconnected(object? sender, EventArgs e)
        {
            try
            {
                ServerDisconnectedEvent?.Invoke(guidStr);
                // 如果正在尝试重连，则直接返回
                //if (isReconnecting)
                //    return;

                //// 设置正在重连标志
                //isReconnecting = true;

                //// 创建并配置定时器
                //reconnectTimer = new System.Timers.Timer();
                //reconnectTimer.Interval = 15000; // 设置重连间隔为15秒
                //reconnectTimer.Elapsed -= ReconnectTimer_Elapsed;

                //reconnectTimer.Elapsed += ReconnectTimer_Elapsed;
                //reconnectTimer.AutoReset = false; // 设置为false，确保每次触发Elapsed事件后只执行一次

                //// 启动定时器
                //reconnectTimer.Start();
            }
            catch(Exception ex)
            {
                AppLog.WriteError("Client_ServerDisconnected断连" + ex.StackTrace + ex.Message);
            }  
        }
        private void ReconnectTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            // 在定时器触发时执行重连操作
            ClientStartConnectToServer(this.ServerIP,this.ServerPort,true);
        }
        private void Client_ServerConnected(object? sender, EventArgs e)
        {
            ServerConnectedEvent?.Invoke();
        }
        /// <summary>
        /// 客户端收到服务器消息时触发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Client_MessageReceived(object? sender, MessageReceivedEventArgs e)
        {
            string msg = Encoding.UTF8.GetString(e.Data);
            if (QuanYiClientMessageEvent != null)
            {
                var qsr = JsonConvert.DeserializeObject<QuanYiServerResponseClass>(msg);
                QuanYiClientMessageEvent.Invoke(qsr);
            }
            if (QuanYiOrderClientMessageEvent != null)
            {
                var qsr = JsonConvert.DeserializeObject<QuanYiOrderServerResponseClass>(msg);
                QuanYiOrderClientMessageEvent.Invoke(qsr);
            }


            #region 处理各种消息（从服务端）
            try
            {
                //AppLog.WriteFatal("orderview收到消息" + e.Data.ToString());
                if (e.Data != null && !string.IsNullOrEmpty(e.Data.ToString()))
                {
                    var tempString = Encoding.UTF8.GetString(e.Data);
                    JObject o = JObject.Parse(tempString);
                    try
                    {
                        if (o["dataType"] != null)
                        {
                           

                            if (o["dataType"].ToString() == "tradeamountlimit")
                            {
                                if ((int)o["data"]["userId"] != UserHelper.UserID)
                                {
                                    return;
                                }
                                int tmp = 0;
                                if (int.TryParse(o["data"]["bidrestVolume"].ToString(), out tmp))
                                {
                                    UserHelper.TradeLimit.MaxBidVolume = tmp;
                                }
                                if (int.TryParse(o["data"]["offerrestVolume"].ToString(), out tmp))
                                {
                                    UserHelper.TradeLimit.MaxOfrVolume = tmp;
                                }
                                AppLog.WriteFatal("359");
                                AppLog.WriteFatal($"最大可买：{UserHelper.TradeLimit.MaxBidVolume},最大可卖：{{UserHelper.TradeLimit.MaxOfrVolume}}");
                                TradeAmountLimitEvent();
                            }
                            if (o["dataType"].ToString().IndexOf("deal_bond") >= 0)
                            {
                                string str = o["data"].ToString();
                                LilyTradeModel lilyTrade = JsonConvert.DeserializeObject<LilyTradeModel>(str, settings);
                                SubscribeLilyTradeEvent(lilyTrade);
                            }
                            if (o["dataType"].ToString().IndexOf("cancel_bond") >= 0)
                            {
                                string str = o["data"].ToString();
                                //LilyTradeModel lilyTrade = JsonConvert.DeserializeObject<LilyTradeModel>(str, settings);
                                //SubscribeLilyTradeEvent(lilyTrade);
                            }

                            if (o["dataType"].ToString().IndexOf("cancel_bond") >= 0)
                            {
                                string str = o["data"].ToString();
                                //LilyTradeModel lilyTrade = JsonConvert.DeserializeObject<LilyTradeModel>(str, settings);
                                //SubscribeLilyTradeEvent(lilyTrade);
                            }

                            if (o["dataType"].ToString() == "qiangping_inform")
                            {
                                try
                                {
                                    // 解析 JSON 消息





                                    if (o != null)
                                    {
                                        //clientWebSocket?.Send("ack"); // 回复服务端ack
                                        LilyInformEvent?.Invoke(o.ToString()); //告知客户端
                                    }
                                    return;
                                }
                                catch (Exception ex)
                                {
                                    AppLog.WriteError("处理强平预警消息异常");
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        AppLog.WriteError(ex.Message + "clientWebSocket" + "Client_MessageReceived1" + ex.StackTrace);
                    }
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "clientWebSocket" + "Client_MessageReceived2" + ex.StackTrace);
            }

            #endregion
        }

        /// <summary>
        /// 收到刘老师服务端的消息。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ClientWebSocket_OnMessage(object? sender, MessageEventArgs e)
        {
            if (e.Data != null)
            {
                
                //AppLog.WriteWarn("收到刘-服务端消息：" + e.Data);
                if (e.Data.IndexOf("ack") > 0)
                {
                    SubscribeTradeSucceeded = true;
                    return;
                }
                string TsCode = "";
                List<BidHistory> Bids = new List<BidHistory>();
                JObject o = JObject.Parse(e.Data);
                //Websocket data for ofr
                if (o["dataType"].ToString() == "noforward_1")
                {
                    TsCode = o["dataKey"].ToString();
                    try
                    {
                        JArray jArray = o["data"] as JArray;
                        //BidHistory bid = new BidHistory();
                        //bid.BidType = BidHistory.enumBidType.Ofr;
                        //bid.Price = decimal.Parse(jArray[0]["price"].ToString());
                        //bid.BrokerName = jArray[0]["brokerName"].ToString();
                        //SubscribeBidEvent(bid);
                        Bids = JsonConvert.DeserializeObject<List<BidHistory>>(o["data"].ToString(), settings);
                        if (SubscribeAllBidEvent != null)
                        {
                            SubscribeAllBidEvent(TsCode, Bids, 1);
                        }
                        return;
                    }
                    catch (Exception ex)
                    {

                    }
                }
                //Websocket data for bid
                if (o["dataType"].ToString() == "noforward_0")
                {
                    TsCode = o["dataKey"].ToString();
                    try
                    {
                        JArray jArray = o["data"] as JArray;
                        //BidHistory bid = new BidHistory();
                        //bid.BidType = BidHistory.enumBidType.Bid;
                        //bid.Price = decimal.Parse(jArray[0]["price"].ToString());
                        //bid.BrokerName = jArray[0]["brokerName"].ToString();
                        //SubscribeBidEvent(bid);
                        Bids = JsonConvert.DeserializeObject<List<BidHistory>>(o["data"].ToString(), settings);
                        if (SubscribeAllBidEvent != null)
                        {
                            SubscribeAllBidEvent(TsCode, Bids, 0);
                        }
                        return;
                    }
                    catch (Exception ex)
                    {

                    }
                }
                //if (o["dataType"].ToString() == "forward_1")
                //{
                //    try
                //    {
                //        JArray jArray = o["data"] as JArray;
                //        //BidHistory bid = new BidHistory();
                //        //bid.BidType = BidHistory.enumBidType.Ofr;
                //        //bid.Price = decimal.Parse(jArray[0]["price"].ToString());
                //        //bid.BrokerName = jArray[0]["brokerName"].ToString();
                //        //bid.Forward = true;
                //        //SubscribeBidEvent(bid);
                //        Bids = JsonConvert.DeserializeObject<List<BidHistory>>(o["data"].ToString(), settings);
                //        if (SubscribeAllBidEvent != null)
                //        {
                //            SubscribeAllBidEvent(Bids, 1);
                //        }
                //        return;
                //    }
                //    catch (Exception ex)
                //    {

                //    }
                //}
                ////Websocket data for bid
                //if (o["dataType"].ToString() == "forward_0")
                //{
                //    try
                //    {
                //        JArray jArray = o["data"] as JArray;
                //        //BidHistory bid = new BidHistory();
                //        //bid.BidType = BidHistory.enumBidType.Bid;
                //        //bid.Price = decimal.Parse(jArray[0]["price"].ToString());
                //        //bid.BrokerName = jArray[0]["brokerName"].ToString();
                //        //bid.Forward = true;
                //        //SubscribeBidEvent(bid);
                //        Bids = JsonConvert.DeserializeObject<List<BidHistory>>(o["data"].ToString(), settings);
                //        if (SubscribeAllBidEvent != null)
                //        {
                //            SubscribeAllBidEvent(Bids, 0);
                //        }
                //        return;
                //    }
                //    catch (Exception ex)
                //    {

                //    }
                //}
                //Websocket data for trade
                if (o["dataType"].ToString() == "trade")
                {
                    try
                    {
                        TradeHistoryRow thr = new TradeHistoryRow();
                        thr.TsCode = o["data"]["tscode"].ToString();
                        thr.TradePrice = decimal.Parse(o["data"]["tradeprice"].ToString());
                        thr.TradeTime = o["data"]["tradetime"].ToString();
                        thr.BrokerName = o["data"]["brokerName"].ToString();
                        thr.DealType = o["data"]["dealtype"].ToString();
                        thr.Forward = bool.Parse(o["data"]["forwardcontact"].ToString());
                        thr.TradeDate = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " " + thr.TradeTime);
                        thr.TradeID = o["data"]["tradeid"].ToString();
                        thr.SettleSpeed = o["data"]["settleSpeed"].ToString();
                        if (thr.DealType == "REF")
                        {
                            thr.Withdraw = true;
                        }
                        if (SubscribeTradeEvent != null)
                        {
                            SubscribeTradeEvent(thr);
                        }
                    }
                    catch (Exception ex)
                    {
                        AppLog.WriteError("ClientWebSocket_OnMessage异常" + ex.Message + ex.StackTrace);
                    }
                
                }

                if (o["dataType"].ToString() == "tradeamountlimit")
                {
                    try
                    {
                        if ((int)o["data"]["userId"] != UserHelper.UserID)
                        {
                            return;
                        }
                        int tmp = 0;
                        {
                            if (int.TryParse(o["data"]["bidrestVolume"].ToString(), out tmp))
                            {
                                UserHelper.TradeLimit.MaxBidVolume = tmp;
                            }
                            if (int.TryParse(o["data"]["offerrestVolume"].ToString(), out tmp))
                            {
                                UserHelper.TradeLimit.MaxOfrVolume = tmp;
                            }
                            AppLog.WriteFatal("583");
                            AppLog.WriteFatal($"最大可买：{UserHelper.TradeLimit.MaxBidVolume},最大可卖：{UserHelper.TradeLimit.MaxOfrVolume}");

                            TradeAmountLimitEvent?.Invoke();
                        }
                        //if (TradeAmountLimitEvent != null)
                        //{
                        //    TradeAmountLimitEvent();
                        //}

                    }
                    catch (Exception ex)
                    {

                    }
                    return;
                }
                return;
    
            }

            if (IsGetTradeLimit)
            {
                if (e.Data != null)
                {
                    JObject o = JObject.Parse(e.Data);
                    try
                    {
                        if (o["dataType"].ToString().Contains("IB"))
                        {
                            return;
                        }

                        if (o["dataType"].ToString() == "tradeamountlimit")
                        {
                            if ((int)o["data"]["userId"] != UserHelper.UserID)
                            {
                                return;
                            }
                            int tmp = 0;
                            if (int.TryParse(o["data"]["bidrestVolume"].ToString(), out tmp))
                            {
                                UserHelper.TradeLimit.MaxBidVolume = tmp;
                            }
                            if (int.TryParse(o["data"]["offerrestVolume"].ToString(), out tmp))
                            {
                                UserHelper.TradeLimit.MaxOfrVolume = tmp;
                            }
                            AppLog.WriteFatal($"最大可买：{UserHelper.TradeLimit.MaxBidVolume},最大可卖：{{UserHelper.TradeLimit.MaxOfrVolume}}");
                            AppLog.WriteFatal("633");
                            TradeAmountLimitEvent();
                        }
                        if (o["dataType"].ToString().IndexOf("deal_bond") >= 0)
                        {
                            string str = o["data"].ToString();
                            LilyTradeModel lilyTrade = JsonConvert.DeserializeObject<LilyTradeModel>(str, settings);
                            SubscribeLilyTradeEvent(lilyTrade);
                        }
                        if (o["dataType"].ToString().IndexOf("cancel_bond") >= 0)
                        {
                            string str = o["data"].ToString();
                            LilyTradeModel lilyTrade = JsonConvert.DeserializeObject<LilyTradeModel>(str, settings);
                            if (SubscribeLilyTradeEvent != null)
                            {
                                SubscribeLilyTradeEvent(lilyTrade);
                            }

                        }
                    }
                    catch (Exception ex)
                    {
                        AppLog.WriteError("ClientWebSocket_OnMessage异常" + ex.Message + ex.StackTrace);
                    }

                }
            }
        }
        #endregion


        #region 管理端

        /// <summary>
        /// 发给服务端线程
        /// </summary>
        private void AdminSendMessageStart()
        {
            try
            {
                client.ServerConnected += Admin_ServerConnected;
                client.ServerDisconnected += Admin_ServerDisconnected;
                client.MessageReceived += Admin_MessageReceived;
                client.KeepAliveInterval = 30;
                client.Start();
            }
            catch (Exception ex)
            {
                AppLog.WriteError("管理端无法连接至服务端" + ex.Message);
            }

        }


        /// <summary>
        /// 管理端收到服务端消息(核心消息） 都是从这发来的
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Admin_MessageReceived(object? sender, MessageReceivedEventArgs e)
        {
            string msg = Encoding.UTF8.GetString(e.Data);
            //Debug.WriteLine(msg);
            //return;
            QuanYiOrderServerResponseClass qsr = null;
            try
            {
                qsr = JsonConvert.DeserializeObject<QuanYiOrderServerResponseClass>(msg);
            }
            catch
            {
                AppLog.WriteError($"解析qsr失败{qsr.ToString()}");
                return;
            }
            if (qsr == null)
            {
                return;
            }
            qsr.SessionID = e.Client.Guid;
            qsr.RemoteIP = e.Client.Ip;
            //AdminMessageEvent("222");
            if (QuanYiOrderServerToAdminMessageEvent != null)
            {
                QuanYiOrderServerToAdminMessageEvent(qsr);
            }
        }

        private void Admin_ServerDisconnected(object? sender, EventArgs e)
        {
            ServerDisconnectedEvent(guidStr);
        }

        private void Admin_ServerConnected(object? sender, EventArgs e)
        {
            ServerConnectedEvent();
        }

        /// <summary>
        /// 核心方法(管理端连接至服务端）
        /// </summary>
        /// <param name="ServerIP"></param>
        /// <param name="ServerPort"></param>
        /// <returns></returns>
        public bool AdminStartConnectToServer(string ServerIP, int ServerPort)
        {
            try
            {
                //string ServerIP = "172.16.10.123";
                this.ServerIP = ServerIP;
                this.ServerPort = ServerPort;
                client = null;
                Uri uri = new Uri($"ws://{ServerIP}:{ServerPort}");
                client = new WatsonWsClient(uri);
                AdminSendMessageStart();
                if (!client.Connected)
                {
                    return false;
                }
                QuanYiServerResponseClass qsr = new QuanYiServerResponseClass();
                qsr.DataType = QuanYiServerResponseClass.DataTypeEnum.Login;
                qsr.UserID = UserHelper.UserID;
                qsr.Token = UserHelper.Token;
                bool res = SendResponseToServer(qsr);
                if (!res)
                {
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "clientWebSocket" + "StartConnection" + ex.StackTrace);
                return false;
            }
        }
        #endregion







        /// <summary>
        /// 心跳监视
        /// </summary>
        private void WatchDogStart()
        {
           
        }


        //public delegate void SubscribeAllBidEventHandle(string TsCode, List<BidHistory> Bids, int BidType);
        //public event SubscribeAllBidEventHandle SubscribeAllBidEvent; //订阅下单事件
        public delegate Task SubscribeAllBidEventHandle(string TsCode, List<BidHistory> Bids, int BidType);
        public event SubscribeAllBidEventHandle SubscribeAllBidEvent; // 订阅下单事件


        private readonly object _clientLock = new object();
        public bool SendResponseToServer(QuanYiServerResponseClass qsr)
        {
            lock (_clientLock)
            {
                try
                {
                    string msg = JsonConvert.SerializeObject(qsr);
                    bool success = false;

                    if (client != null && client.Connected)
                    {
                        success = true;
                    }

                    client?.SendAndWaitAsync(msg); // 发送消息

                    if (!success)
                    {
                        qsr.Code = 5;
                        qsr.Message = "服务器连接超时";
                        AppLog.WriteError(qsr.Message + "ClientWebSocketHelper" + JsonConvert.SerializeObject(qsr));
                    }

                    return true;
                }
                catch (Exception ex)
                {
                    AppLog.WriteError(ex.Message + "ClientWebSocketHelper" + "SendResponseToServer:" + JsonConvert.SerializeObject(qsr), ex.StackTrace);
                    return false;
                }
            }
        }
        public bool SendResponseToServer(QuanYiOrderServerResponseClass qsr)
        {
            try
            {
                lock(_clientLock)
                {
                    string msg = JsonConvert.SerializeObject(qsr);
                    Task<bool> res = client.SendAsync(msg, System.Net.WebSockets.WebSocketMessageType.Text);
                    res.Wait();
                    if (!res.Result)
                    {
                        qsr.Code = 5;
                        qsr.Message = "服务器连接超时";
                        return false;
                    }

                    //QuanYiClientMessageEvent(qsr);
                    return true;
                }
               
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "ClientWebSocketHelper" + "SendResponseToServer:" + JsonConvert.SerializeObject(qsr), ex.StackTrace);
                return false;
            }
        }
        public async Task SendResponseToServerAsync(QuanYiOrderServerResponseClass qsr)
        {
            try
            {
                string msg = JsonConvert.SerializeObject(qsr);
                bool res = await client.SendAsync(msg, System.Net.WebSockets.WebSocketMessageType.Text);

                if (!res)
                {
                    qsr.Code = 5;
                    qsr.Message = "服务器连接超时";
                }
                //QuanYiClientMessageEvent(qsr);
                return;
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "ClientWebSocketHelper" + "SendResponseToServer:" + JsonConvert.SerializeObject(qsr), ex.StackTrace);
                return;
            }
        }

        public string tempStr = string.Empty;
        public string guidStr = string.Empty;
        /// <summary>
        /// 订阅交易数据（根据券码获得）---这个方法是和刘老师互动的
        /// </summary>
        /// <param name="TsCode"></param>
        public void SubscribeTradeData(string TsCode,string guid=null)
        {
            guidStr = guid;
            AppLog.WriteInfo("下单界面调用 SubscribeTradeData");
            //if (clientWebSocket == null||clientWebSocket.ReadyState== WebSocketState.Open)
            {
                if(clientWebSocket!=null)
                {
                    clientWebSocket.OnClose -= ClientWebSocket_OnClose1;
                    //if(clientWebSocket.ReadyState==WebSocketState.Open)
                    //{
                    //    AppLog.WriteInfo("SubscribeTradeData无需调用，因为连接连接着");
                    //    return;
                    //}
                }
                AppLog.WriteError("SubscribeTradeData调用了，orderviewmodel --websocket重连");
                clientWebSocket?.Close();
                tempStr = TsCode;
                //log.Info("Start WebSocket", "", "");
                clientWebSocket = new WebSocket(serverUri);
                clientWebSocket.OnMessage -= ClientWebSocket_OnMessage;

                clientWebSocket.OnMessage += ClientWebSocket_OnMessage;
                clientWebSocket.OnError -= ClientWebSocket_OnError;
                                                         
                clientWebSocket.OnError += ClientWebSocket_OnError;

                clientWebSocket.OnClose -= ClientWebSocket_OnClose1;

                clientWebSocket.OnClose += ClientWebSocket_OnClose1;

                clientWebSocket.OnOpen -= ClientWebSocket_OnOpen1;
                                                            
                clientWebSocket.OnOpen += ClientWebSocket_OnOpen1;
                clientWebSocket.Connect();
            }

            if (clientWebSocket.ReadyState == WebSocketState.Open)
            {
                AppLog.WriteInfo("下单界面和lily打通");
            }
            SubscribeTradeSucceeded = false;
            string subString = $"{{\"dataKey\": \"{TsCode}\", \"dataType\": \"sub_tscode\",\"data\":{{\"subType\":0}}}}";
            try
            {
                if (clientWebSocket.ReadyState == WebSocketState.Open)
                {
                    if (string.IsNullOrEmpty(subString))
                    {

                        AppLog.WriteWarn("SubscribeTradeData的substring为空异常");
                        return;
                    }
                    clientWebSocket.Send(subString);
                }
                
                //int iRetry = 0;
                //while (!SubscribeTradeSucceeded)
                //{
                //    iRetry++;
                //    if (iRetry > 10)
                //    {
                //        clientWebSocket.Send(subString);
                //        break;
                //    }
                //    Task.Delay(1000);

                //    clientWebSocket.Connect();
                //}
            }
            catch (WebSocketException ex)
            {
                try
                {
                    //clientWebSocket = new WebSocket(serverUri);
                    //clientWebSocket.Connect();
                    AppLog.WriteError(ex.Message + "AA---ClientWebSocketHelper" + "SubscribeTradeData" + ex.Message + ex.StackTrace);

                }
                catch
                {
                    AppLog.WriteError(ex.Message + "ClientWebSocketHelper"+ "SubscribeTradeData" + ex.Message + ex.StackTrace);
                }
            }

        }

        private void ClientWebSocket_OnError(object? sender, WebSocketSharp.ErrorEventArgs e)
        {
            AppLog.WriteError("下单界面与Lily连接异常了！" + e.Message);
        }

        private void ClientWebSocket_OnOpen1(object? sender, EventArgs e)
        {
            //LilyWebSocketConnectedEvent?.Invoke(this.guidStr);
            AppLog.WriteInfo("下单界面与lily的连接开启！");

        }

        private void ClientWebSocket_OnClose1(object? sender, CloseEventArgs e)
        {
            AppLog.WriteError("下单界面与lily的连接关闭。。。");
            //if(!string.IsNullOrEmpty(this.tempStr))
            //{
            //    this.SubscribeTradeData(this.tempStr);
            //}
            //LilyWebSocketDisconnectedEvent?.Invoke();
            if (tempI==0)
            {
                AppLog.WriteError("ClientWebSocket_OnClose1 I=0 重连");
             
            }
            else
            {
                AppLog.WriteError("ClientWebSocket_OnClose1 I=1 不重连");
            }
         
        }


        /// <summary>
        /// 订阅龙虎榜
        /// </summary>
        public async Task SubscribeVolumeIndex()
        {
            try
            {
                //if (clientWebSocket == null || IsLonghuWebSocketConnected)
                {
                    if(clientWebSocket!=null)
                    {
                        clientWebSocket.OnClose -= LonghuWebSocketClosed;
                    }
                    clientWebSocket?.Close();
                    clientWebSocket = new WebSocket(serverUri);

                    // 确保事件只注册一次
                    clientWebSocket.OnOpen -= LongHuWebSocket_OnOpen;
                    clientWebSocket.OnClose -= LonghuWebSocketClosed;
                    clientWebSocket.OnMessage -= HandleLonghuMessage;

                    clientWebSocket.OnError -= LongHuLilyWebSocket_OnError;

                    clientWebSocket.OnError += LongHuLilyWebSocket_OnError;
                    clientWebSocket.OnOpen += LongHuWebSocket_OnOpen;
                    clientWebSocket.OnClose += LonghuWebSocketClosed;
                    clientWebSocket.OnMessage += HandleLonghuMessage;

                    clientWebSocket.Connect();

                    // 等待连接成功
                    int retryCount = 0;
                    while (!IsLonghuWebSocketConnected)
                    {
                        retryCount++;
                        AppLog.WriteWarn($"AA龙虎榜重连第{retryCount}次");
                        await Task.Delay(5000); // 每次重试前等待1秒
                    }
                }
                //else
                //{
                //    // 如果已经连接，确保事件已注册
                //    clientWebSocket.OnClose -= LonghuWebSocketClosed;
                //    clientWebSocket.OnClose += LonghuWebSocketClosed;
                //    clientWebSocket.OnMessage -= HandleLonghuMessage;

                //    clientWebSocket.OnMessage += HandleLonghuMessage;
                //}

                if (IsLonghuWebSocketConnected)
                {
                    // 发送订阅请求
                    AppLog.WriteInfo("龙虎榜发送订阅请求。");
                    string subString = "{\"dataKey\": \"\", \"dataType\": \"rank\"}";
                    clientWebSocket.Send(subString);

                    // 重试机制
                    //int iRetry = 0;
                    //while (!SubscribeVolumeSucceeded)
                    //{
                    //    iRetry++;

                    //    AppLog.WriteWarn($"BB龙虎榜重连第{iRetry}次");
                    //    await Task.Delay(5000);
                    //    if (!SubscribeVolumeSucceeded)
                    //    {
                    //        clientWebSocket.Send(subString);
                    //    }
                    //}
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError("订阅龙虎榜SubscribeVolumeIndex异常" + ex.Message + "-" + ex.StackTrace);
            }
           
        }

        private void LongHuLilyWebSocket_OnError(object? sender, WebSocketSharp.ErrorEventArgs e)
        {
            AppLog.WriteError($"LilyWebSocket_OnError - 龙虎榜 与 Lily 连接 OnError: {e.Message}");
        }

        public bool IsLonghuWebSocketConnected = false;
        public void UnsubscribeVolumeIndex()
        {
            if (clientWebSocket != null)
            {

                clientWebSocket?.Close();
            }
          
        }
        private void LongHuWebSocket_OnOpen(object? sender, EventArgs e)
        {
            IsLonghuWebSocketConnected= true;   
            AppLog.WriteInfo("成功订阅龙虎榜！");
       
        }

        private void HandleLonghuMessage(object? sender, MessageEventArgs e)
        {
            if (e.Data != null)
            {
                if (e.Data.IndexOf("ack") > 0)
                {
                    SubscribeVolumeSucceeded = true;
                    return;
                }

                JObject o = JObject.Parse(e.Data);
                if (o["dataType"].ToString() == "rank")
                {
                    List<VolumeIndex> index;
                    try
                    {
                        index = JsonConvert.DeserializeObject<List<VolumeIndex>>(o["data"].ToString(), settings);
                        SubscribeIndexEvent(index);
                    }
                    catch (Exception ex)
                    {
                        AppLog.WriteError($"Error parsing message: {ex.Message}");
                    }
                }
            }
        }

        private async void LonghuWebSocketClosed(object? sender, CloseEventArgs e)
        {
            AppLog.WriteError("订阅龙虎榜断连了！");
            IsLonghuWebSocketConnected = false;
            //Messenger.Default.Send("111","longhuClosed");
            //while (clientWebSocket.ReadyState != WebSocketState.Open)
            //{
            //    try
            //    {
            //        clientWebSocket = new WebSocket(serverUri);
            //        clientWebSocket.OnClose -= LonghuWebSocketClosed;

            //        clientWebSocket.OnClose += LonghuWebSocketClosed;
            //        clientWebSocket.OnMessage -= HandleLonghuMessage;

            //        clientWebSocket.OnMessage += HandleLonghuMessage;
            //        clientWebSocket.Connect();

            //        if (clientWebSocket.ReadyState == WebSocketState.Open)
            //        {
            //            AppLog.WriteInfo("成功订阅龙虎榜！");
            //        }
            //    }
            //    catch (Exception ex)
            //    {
            //        AppLog.WriteError($"WebSocket连接异常: {ex.Message}");
            //    }
            //    await Task.Delay(5000);
            //}
        }


        public async Task SubscribeVolumeIndexAsync()
        {
            if (clientWebSocket == null)
            {
                //log.Info("Start WebSocket", "", "");
                clientWebSocket = new WebSocket(serverUri);
                clientWebSocket.ConnectAsync();
            }

            clientWebSocket.OnMessage += async (sender, e) =>
            {
                if (e.Data != null)
                {
                    if (e.Data.IndexOf("ack") > 0)
                    {
                        SubscribeVolumeSucceeded = true;
                        return;
                    }
                    JObject o = JObject.Parse(e.Data);
                    if (o["dataType"].ToString() == "rank")
                    {
                        List<VolumeIndex> index = new List<VolumeIndex>();
                        try
                        {
                            index = JsonConvert.DeserializeObject<List<VolumeIndex>>(o["data"].ToString(), settings);
                            try
                            {
                                SubscribeIndexEvent?.Invoke(index);
                            }
                            catch (Exception ex)
                            {
                                // Log or handle the exception
                            }
                            return;
                        }
                        catch (Exception ex)
                        {
                            // Log or handle the exception
                        }
                    }
                }
            };

            string subString = $"{{\"dataKey\": \"\", \"dataType\": \"rank\"}}";
            clientWebSocket.SendAsync(subString,null);


            clientWebSocket.OnClose += (s, e) =>
            {
                AppLog.WriteError("龙虎榜订阅Lily关闭了！");
            };
            int iRetry = 0;
            while (!SubscribeVolumeSucceeded)
            {
                iRetry++;
                if (iRetry > 10)
                {
                    clientWebSocket.SendAsync(subString,null);
                    break;
                }
                await Task.Delay(1000);
            }
        }

        private void ClientWebSocket_OnClose(object? sender, CloseEventArgs e)
        {
            
        }

        public WatsonWsClient client; // 和服务端交互的websocket
        public  WebSocket clientWebSocket; //和serverUri绑定的（lily）

        public string ServerIP { get; set; }
        public int ServerPort { get; set; }




        #region 我的服务端（充当客户端）订阅刘老师的服务端

        public void UnSubscribeLilyServerData()
        {

            clientWebSocket.OnClose -= LilyWebSocket_OnClose;
            clientWebSocket.OnClose += LilyWebSocket_OnClose;
            clientWebSocket?.Close();

        }

        public bool IsOrderListViewModel = false;
        public bool IsOrderViewModel = false;
        public bool IsServerViewModel = false;//是否是服务端


        /// <summary>
        /// 1、订阅强平消息，datakey="qiangping",
        /// data=
        //"volume": 100,         
        //"dealType": "buy",         
        //"userTradeID": 1234567890,         
        //"userID": 987,         
        //"tsCode": "AAPL",         
        //"brokerID": 456,         
        //"price": 345.67,         
        //"deliveryDate": "2024-06-30",
        //"dataType": "qiangping"         
        /// </summary>
        /// <param name="TsCode"></param>
        /// 0和1 区分 客户端还是服务端的订阅，客户端为0，服务端为1,OrderListViewModel=2,OrderView=3
        public async Task<bool> SubscribeLilyServerData(int i=0)
        {
            try
            {
                if (i == 2)
                {
                    IsOrderListViewModel = true;
                }
                if (clientWebSocket == null || clientWebSocket.ReadyState == WebSocketState.Closed|| !IsOrderListViewModelWebSocketConnected)
                {
                    //log.Info("Start WebSocket", "", "");
                    clientWebSocket = new WebSocket(serverUri);
                    clientWebSocket.OnMessage -= LilyWebSocket_OnMessage;

                    clientWebSocket.OnMessage += LilyWebSocket_OnMessage;
                    clientWebSocket.OnClose -= LilyWebSocket_OnClose;
                    clientWebSocket.OnClose += LilyWebSocket_OnClose;

                    clientWebSocket.OnError -= LilyWebSocket_OnError;
                    clientWebSocket.OnError += LilyWebSocket_OnError;

                    clientWebSocket.OnOpen -= LilyWebSocket_OnOpen;
                    clientWebSocket.OnOpen += LilyWebSocket_OnOpen;
                    clientWebSocket.Connect();
                    AppLog.WriteInfo("OrderListViewModel尝试连接lily！websocket");
                    //Thread.Sleep(1000);


                }
                if(clientWebSocket==null)
                {
                    return false;
                }
                var temp = clientWebSocket.ReadyState;
                if (temp == WebSocketState.Open)
                {
                   if(i==3)
                    {
                        IsOrderViewModel = true;
                    }
                    
                    if (i == 1)
                    {
                        IsServerViewModel = true;
                        string subString = $"{{\"dataKey\": \"\", \"dataType\": \"sub_qiangping\"}}";
                        clientWebSocket.Send(subString);
                        AppLog.WriteInfo("服务端订阅强平_sub_qiangping");
                        SubscribeLilySucceeded = true;
                        // 启动心跳包发送
                        Task.Run(() => SendHeartBeatAsync());
                 
                        AppLog.WriteInfo("服务端发送心跳");

                        return true;
                    
                    }
                    AppLog.WriteInfo("成功连接至lily！websocket");
                    
                    return true;
                }
                else
                {
                    //return false;
                }



                //SubscribeLilySucceeded = false;
                try
                {

                    int iRetry = 0;
                    // 等待连接成功
                    int retryCount = 0;
                    while (!IsOrderListViewModelWebSocketConnected)
                    {
                        retryCount++;
                        AppLog.WriteWarn($"AAOrderListViewModel -- Websocket 重连第{retryCount}次");
                        await Task.Delay(5000); // 每次重试前等待1秒
                    }
                    return true;


                }
                catch (WebSocketException ex)
                {

                    try
                    {
                        clientWebSocket = new WebSocket(serverUri);
                        clientWebSocket.Connect();
                        Thread.Sleep(1000);
                        if (clientWebSocket.ReadyState != WebSocketState.Open)
                        {
                            return false;
                        }
                    }
                    catch
                    {
                        AppLog.WriteError(ex.Message + "ClientWebSocketHelper" + "SubscribeLilyServerData" + ex.Message + ex.StackTrace);
                    }

                }
                finally
                {

                }
                return true;
            }
            catch(Exception ex)
            {
                AppLog.WriteError("orderlistviewmodel订阅lily出错" + ex.Message + ex.StackTrace);
                return false;
            }
            

        }
        public bool IsOrderListViewModelWebSocketConnected=false;
        private bool _isHeartbeatRunning = false; // 标志位，防止多次启动心跳任务
        private void LilyWebSocket_OnOpen(object? sender, EventArgs e)
        {
            if(IsOrderViewModel)
            {
                AppLog.WriteInfo("OrderViewModel---与Lily连接");
                LilyWebSocketConnectedEvent?.Invoke(this.guidStr);
            }
            if (IsOrderListViewModel)
            {
                IsOrderListViewModelWebSocketConnected = true;

                AppLog.WriteInfo("orderlistviewmodel成功和lily连接");
                // 取消并清理之前的心跳任务
                StopHeartbeat();
                Task.Run(() => SendHeartBeatAsync());
            }
            
            
           
      
            //if (!_isHeartbeatRunning)
            //{
            //    _isHeartbeatRunning = true;
               
            //}
        }

        private void StopHeartbeat()
        {
            if (heartbeatCts != null&&!heartbeatCts.IsCancellationRequested)
            {
                heartbeatCts.Cancel(); // 请求取消心跳任务
                heartbeatCts.Dispose(); // 释放资源
                heartbeatCts = new CancellationTokenSource();
            }
        }

        private void LilyWebSocket_OnError(object? sender, WebSocketSharp.ErrorEventArgs e)
        {
            AppLog.WriteError($"LilyWebSocket_OnError - 与 Lily 连接 OnError: {e.Message}");
            
        }

        /// <summary>
        /// 我的服务端给刘老师的服务端发送心跳
        /// </summary>
        private CancellationTokenSource heartbeatCts = new CancellationTokenSource();

        public async Task SendHeartBeatAsync()
        {
            try
            {
                // 初始延迟
                await Task.Delay(30000, heartbeatCts.Token);

                string heartBeat = "{\"dataKey\":\"HELLO\",\"dataType\":\"ping\"}";
                var messageBytes = Encoding.UTF8.GetBytes(heartBeat);
                while (!heartbeatCts.Token.IsCancellationRequested)
                {
                    if (clientWebSocket != null && clientWebSocket.ReadyState == WebSocketState.Open)
                    {
                        try
                        {
                            AppLog.WriteInfo("向Lily发送心跳包。");
                            clientWebSocket.Send(heartBeat);
                        }
                        catch (Exception ex)
                        {
                            AppLog.WriteError("发送心跳包时出错: " + ex.Message);
                            SubscribeLilySucceeded = false;
                            //ReconnectEvent();
                        }
                    }

                    // 等待下一次发送心跳包
                    await Task.Delay(30000, heartbeatCts.Token);
                }
            }
            catch (Exception ex)
            {
                // 任务被取消，不需要处理
                AppLog.WriteError("SendHeartBeatAsync异常"+ex.Message);
            }
        }



        private void LilyWebSocket_OnClose(object? sender, CloseEventArgs e)
        {
            this.clientWebSocket = null;

            AppLog.WriteError("LILY断连了。LilyWebSocket_OnClose");
            //_isHeartbeatRunning = false;
            if(IsOrderViewModel)
            {
                AppLog.WriteError("下单界面与lily断连接，OrderViewModelLilyWebSocket_OnClose");
                LilyWebSocketDisconnectedEvent?.Invoke();
            }
            //if (IsOrderListViewModel)
            //{
            //    IsOrderListViewModelWebSocketConnected = false;
            //    AppLog.WriteError("与lily断连接，OrderListViewModelLilyWebSocket_OnClose,停止发送心跳");
            //    Messenger.Default.Send("111", "orderListViewModelWebSocketClosed");
            //}
            if (IsOrderListViewModel)
            {
                IsOrderListViewModelWebSocketConnected = false;
                AppLog.WriteError("OrderListViewModel与lily断连接，LilyWebSocket_OnClose");
                LilyDisconnectEvent?.Invoke();
            }
            if (IsServerViewModel)
            {
                AppLog.WriteError("IndexServerViewmodel与lily断连接，LilyWebSocket_OnClose");
                LilyDisconnectEvent?.Invoke();
            }
        }

      

        /// <summary>
        /// 我的服务端订阅刘老师服务端
        /// 1、qiangping
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LilyWebSocket_OnMessage(object? sender, MessageEventArgs e)
        {
           if (e.Data != null)
            {


                //AppLog.WriteFatal(e.Data);
                SubscribeLilySucceeded = true;
                if (e.Data.IndexOf("ack") > 0)
                {
                    SubscribeLilySucceeded = true;
                    return;
                }
                string TsCode = "";
                List<BidHistory> Bids = new List<BidHistory>();
                JObject o = JObject.Parse(e.Data);
                //Websocket data for ofr

                try
                {

                
                if (o != null)
                {
                        if (o["dataType"].ToString() == "chat_message")
                        {
                            try
                            {
                                
                                //clientWebSocket?.Send("ack"); // 回复服务端ack
                                LilyInformEvent?.Invoke(o.ToString());
                              
                                return;
                            }
                            catch (Exception ex)
                            {
                                AppLog.WriteError("处理强平消息异常");
                            }
                        }else
                        {
                            //clientWebSocket?.Send("ack"); // 回复服务端ack
                            LilyInformEvent?.Invoke(o.ToString());
                        }
        
                }
                }
                catch(Exception ex)
                {
                    AppLog.WriteError("服务端LilyWebSocket_OnMessage异常" + ex.StackTrace + ex.Message);
                }
                return;
                //if (o["dataType"].ToString() == "qiangping_inform")
                //{
                //    try
                //    {
                //        // 解析 JSON 消息

                       
                       


                //        if (o != null)
                //        {
                //            clientWebSocket?.Send("ack"); // 回复服务端ack
                //            QiangpingInformEvent?.Invoke(o.ToString());
                //        }
                //        return;
                //    }
                //    catch (Exception ex)
                //    {
                //        AppLog.WriteError("处理强平预警消息异常");
                //    }
                //}

            }
        }
        #endregion










        #region 客户端委托
        public delegate void QuanYiClientMessageEventHandle(QuanYiServerResponseClass QSR);
        public  event QuanYiClientMessageEventHandle QuanYiClientMessageEvent;

        public delegate void QuanYiOrderClientMessageEventHandle(QuanYiOrderServerResponseClass QSR);
        public  event QuanYiOrderClientMessageEventHandle QuanYiOrderClientMessageEvent;

        public delegate void ServerDisconnectedEventHandle(string guid);
        public event ServerDisconnectedEventHandle ServerDisconnectedEvent;

        public delegate void ServerConnectedEventHandle();
        public event ServerConnectedEventHandle ServerConnectedEvent;

        public event ServerDisconnectedEventHandle LilyWebSocketConnectedEvent;

        public event ServerConnectedEventHandle LilyWebSocketDisconnectedEvent;
        
        public delegate void TradeAmountLimitHandle();
        public  event TradeAmountLimitHandle TradeAmountLimitEvent; //交易限额？

        public delegate void SubscribeLilyTradeEventHandle(LilyTradeModel Trade);
        public  event SubscribeLilyTradeEventHandle SubscribeLilyTradeEvent;//订阅lily交易

        public delegate Task SubscribeTradeEventHandle(TradeHistoryRow Trade);
        public event SubscribeTradeEventHandle SubscribeTradeEvent;//订阅交易



        public delegate void SubscribeIndexEventHandle(List<VolumeIndex> Index);
        public event SubscribeIndexEventHandle SubscribeIndexEvent; // 订阅龙虎榜数据
        #endregion

        #region 管理端委托
        public delegate void AdminMessageEventHandle(string message);

        public event AdminMessageEventHandle AdminMessageEvent;

        public delegate void QuanYiOrderServerMessageEventHandle(QuanYiOrderServerResponseClass QSR);

        public event QuanYiOrderServerMessageEventHandle QuanYiOrderServerToAdminMessageEvent;


        #endregion

        #region 静态方法
        bool IsGetTradeLimit = false;
        public void GetTradeLimit()
        {
            if (UserHelper.TradeLimit == null)
            {
                UserHelper.TradeLimit = new UserTradeLimit();
            }

            //UserHelper.TradeLimit.InitMaxVolume = _dailyData.GetLilyTradeLimit(UserHelper.UserID);
            IsGetTradeLimit = true;
           
        }
        public int tempI = 0;
        public void CancelLily(int v=0)
        {
            //clientWebSocket.OnClose -= ClientWebSocket_OnClose1;

            //clientWebSocket.OnClose += ClientWebSocket_OnClose1;
            tempI = v;
            this.clientWebSocket?.Close();
        }

        public void CancelLxwServer(int v = 0)
        {
            if(client!=null)
            {
                client.ServerDisconnected -= LxwServer1Disconnected;

                client.ServerDisconnected += LxwServer1Disconnected;
                client.ServerConnected -= LxwServerConnected;
                client.ServerConnected += LxwServerConnected;

                tempI = v;
                this.client?.Stop();
            }else
            {
                this.ClientStartConnectToServer(ServerIP, 38888);
            }

         
        }

        private void LxwServerConnected(object? sender, EventArgs e)
        {
            AppLog.WriteInfo("lxw服务端连接成功");
        }

        private void LxwServer1Disconnected(object? sender, EventArgs e)
        {
            AppLog.WriteError("与lxw服务端连接——断连！");
        }

        public async void ReplyToLily(string replyMsg)
        {
            try
            {
                if (clientWebSocket != null && clientWebSocket.ReadyState == WebSocketState.Open)
                {
                    // 将消息转为字节数组
                    var buffer = Encoding.UTF8.GetBytes(replyMsg);
                    var segment = new ArraySegment<byte>(buffer);

                    //// 将 ArraySegment<byte> 转换为 byte[]
                    //byte[] buffer2 = new byte[segment.Count];
                    //Array.Copy(segment.Array, segment.Offset, buffer, 0, segment.Count);
                    // 通过 WebSocket 发送消息
                    //await clientWebSocket.SendAsync(segment, WebSocketMessageType.Text, true, CancellationToken.None);
                    clientWebSocket.Send("1111");
                    AppLog.WriteInfo("通过 WebSocket 发送回复消息：" + 111);
                }
                else
                {
                    AppLog.WriteError("WebSocket 连接未打开，无法发送回复消息");
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError("发送 WebSocket 回复消息时发生异常：" + ex.Message + ex.StackTrace);
            }
        }
        public bool Test()
        {
            return true;
        }
        //public void ReplyToLily(string v)
        //{
        //    if (this.client != null)
        //    {
        //    }
        //}
        #endregion

        #region 对接刘老师的委托
        public delegate void QiangpingEventHandle(QiangPingInform qiangPingOrder);

        public event QiangpingEventHandle QiangpingEvent; //直接强平


        public delegate void LliyInformEventHandle(string Message);

        public event LliyInformEventHandle LilyInformEvent; //刘老师的各种消息（包括强平、聊天）

        public delegate void LilyDisconnectEventHandle();

        public event LilyDisconnectEventHandle LilyDisconnectEvent; //刘老师的各种消息（包括强平、聊天）
        #endregion


        public delegate void SubscribeAllWebSocketLiuMessages(string message);

        public event SubscribeAllWebSocketLiuMessages AllWebSocketMessagesReceived; //收刘老师所有websocket消息

    }


}
